package com.newlink.building.userinfo.fragment.message

import android.os.Looper
import android.view.View
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.constant.Base_KcpRquestType
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_MESSAGE_LOCAL_UNREAD
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.MessageCleanRequest
import com.newlink.building.common_base.model.bean.MessageListArrayData
import com.newlink.building.common_base.model.bean.MessageListRequest
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.activity.Module_UserInfo_MessageCenterDetailActivityNL
import com.newlink.building.userinfo.adapter.Module_UserInfo_MessageCenterAdapter
import com.newlink.building.userinfo.databinding.FragmentLocalMsgBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_LocalMsgPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_LocalMsgContract
import org.greenrobot.eventbus.EventBus

/**
 * @Author: Jake
 * @Date: 2023-12-11
 * @Description:
 */
class Module_UserInfo_LocalMsgFragment : BaseMvpFragment<Module_UserInfo_LocalMsgContract.View, Module_UserInfo_LocalMsgContract.Presenter>(),
    Module_UserInfo_LocalMsgContract.View {

    private val weakHandler by lazy { WeakHandler(Looper.getMainLooper()) }
    private var curPage: Int = 1
    private var curLimit: Int = 20
    private var curList: MutableList<MessageListArrayData> = mutableListOf()
    private var mAdapter: Module_UserInfo_MessageCenterAdapter? = null
    private var isRefreshLayoutRequest: Boolean = true
    private var emptyContent: View? = null
//    override fun attachLayoutRes(): Int = R.layout.fragment_local_msg

    private lateinit var mBinding: FragmentLocalMsgBinding
    override fun attachLayoutRes(): View {
        mBinding = FragmentLocalMsgBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun createPresenter(): Module_UserInfo_LocalMsgContract.Presenter = Module_UserInfo_LocalMsgPresenter()

    override fun initView(view: View) {
        emptyContent = view.findViewById(R.id.empty_content)
        initAdapter(curList)
        mBinding.swipeRefreshLayout.setOnRefreshListener {
            weakHandler.postDelayed({
                isRefreshLayoutRequest = true
                curPage = 1
                mPresenter?.getMessageList(MessageListRequest(accessToken, curPage, curLimit))
//                showToast(getString(R.string.default_list_data_refresh))
            }, 500)
        }
    }

    override fun lazyLoad() {

    }

    private fun initAdapter(mMessageCenterList: MutableList<MessageListArrayData>) {
        if (mAdapter == null && curPage == 1) {
//            curList = mMessageCenterList
            mAdapter = Module_UserInfo_MessageCenterAdapter(curList)
            mAdapter?.addChildClickViewIds(
                R.id.cl
            )
            mAdapter?.setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.cl -> {
                        curList?.get(position)
                            ?.let { Module_UserInfo_MessageCenterDetailActivityNL.startSelf(activity, it, position) }
                    }
                }
            }

            mAdapter?.run {
                loadMoreModule.setOnLoadMoreListener {
                    if (curList.size <= curLimit) {
                        mAdapter?.loadMoreModule?.isEnableLoadMore = false
                        return@setOnLoadMoreListener
                    }
                    mAdapter?.loadMoreModule?.isEnableLoadMore = true
                    ++curPage
                    mBinding.swipeRefreshLayout.isRefreshing = false
//                    mPresenter?.getMessageList(MessageListRequest(accessToken,userId.toString(),KcpRquestType.TYPE_MESSAGE_LIST,
//                        ListRequestBody(curPage,curLimit)))
                    loadLocalMessageList(curPage)
                }
            }

            mBinding.rvMessageCenter.adapter = mAdapter
        } else {
            mAdapter?.setNewOrAddData(false, mMessageCenterList)
        }

        if (curList == null || curList.size == 0) {
            emptyContent?.visibility = View.VISIBLE
            mBinding.rvMessageCenter.visibility = View.GONE
        } else {
            emptyContent?.visibility = View.GONE
            mBinding.rvMessageCenter.visibility = View.VISIBLE
        }
    }

    override fun hideLoading() {
        super.hideLoading()
        mBinding.swipeRefreshLayout.isRefreshing = false
    }

    override fun getMessageListSuccess(list: MutableList<MessageListArrayData>) {
        hideLoading()
        if (isRefreshLayoutRequest) {
            isRefreshLayoutRequest = false
            curList?.clear()
        }
        EventBus.getDefault().post(MessageEvent(TYPE_MESSAGE_LOCAL_UNREAD, 0))
        if (list.size > 0) {
            for (data in list) {
                if (data.readFlag == 0) {
                    NLog.e("[jake] >>>>>>>>>>>> 本地有未读消息")
                    EventBus.getDefault().post(MessageEvent(TYPE_MESSAGE_LOCAL_UNREAD, 1))
                    break
                }
            }
        }
        NLog.e("[jake]-----local get message list success -----111-----${curList.size}")
        initAdapter(list)

    }

    override fun getMessageListFail() {
        hideLoading()
        ToastUtils.showTextToast(requireContext(), "获取消息列表失败")
    }

    override fun deleteAllMessageListSuccess() {
        NLog.e("[jake] ..... deleteAllMessageListSuccess")
        hideLoading()
        curList?.clear()

        curPage = 1
        loadLocalMessageList(1)
        ToastUtils.showTextToast(requireContext(), getString(R.string.user_msg_delete_success))
    }

    override fun deleteAllMessageListFail() {
        NLog.e("[jake] ..... deleteAllMessageListFail")
        hideLoading()
        showToast(getString(R.string.default_delete_fail))
    }

    fun deleteAllMessageList() {
        NLog.e("[jake]-----do local delete all ----------")
        if (curList?.size!! <= 0) {
            ToastUtils.showTextToast(getString(R.string.user_msg_none_need_delete))
            return
        }
        showLoading()
        mPresenter?.deleteAllMessageList(
            MessageCleanRequest(
                accessToken,
                userId.toString(),
                Base_KcpRquestType.TYPE_MESSAGE_CLEAN
            )
        )
    }

//    override fun onVisible() {
//        super.onVisible()
//        curList?.clear()
//        NLog.e("[jake] local msg fragment ... lazy load")
//        curPage = 1
//        loadLocalMessageList(1)
//    }

    override fun onResume() {
        super.onResume()
        curList?.clear()
        NLog.e("[jake] local msg fragment ... lazy load")
        curPage = 1
        loadLocalMessageList(1)
    }

    private fun loadLocalMessageList(page: Int) {
        showLoading()
        mPresenter?.getMessageList(
            MessageListRequest(accessToken, page, curLimit)
        )
    }

    override fun onInvisible() {
        super.onInvisible()
        NLog.e("[jake] local msg fragment ..onInvisible")
    }

    fun isCurListNull(): Boolean {
        if (curList?.size!! <= 0) {
            return true
        }
        return false
    }
}